package cn.wolfcode.luowowo.resolver;

import cn.wolfcode.luowowo.annotation.UserParam;
import cn.wolfcode.luowowo.domain.UserInfo;
import cn.wolfcode.luowowo.redis.redisService.IUserInfoRedisService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.MethodParameter;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

import javax.servlet.http.HttpServletRequest;

/**
 * 能将控制器中的请求映射方法中的形惨 UserInfo userInfo 转成真是的当前登录用户对象
 */
@Component
public class UserInfoArgumentResolver implements HandlerMethodArgumentResolver {

    @Autowired
    private IUserInfoRedisService userInfoRedisService;

    /**
     * 1.表示当前的参数解析器 支持哪一种参数解析
     * 2.当前可以解析 UserInfo类型的参数
     * 2.如果返回true 表示可以该参数解析器UserInfoArgumentResolver 可以支持UserInfo解析
     *
     * @param methodParameter
     * @return
     */
    @Override
    public boolean supportsParameter(MethodParameter methodParameter) {

        return methodParameter.getParameterType() == UserInfo.class
                && methodParameter.hasParameterAnnotation(UserParam.class);
    }

    /**
     * 执行参数解析器的逻辑 : 把请求映射方法中的 UserInfo对象 转换成真正的当前登录用户对象
     * 当上面的supportsParameter方法 返回true  才会执行当前resolveArgument方法
     */
    @Override
    public Object resolveArgument(MethodParameter methodParameter,
                                  ModelAndViewContainer modelAndViewContainer,
                                  NativeWebRequest nativeWebRequest,
                                  WebDataBinderFactory webDataBinderFactory) throws Exception {
        HttpServletRequest request = nativeWebRequest.getNativeRequest(HttpServletRequest.class);
        //通过请求头获取令牌
        String token = request.getHeader("token");
        //在缓存中获取当前登录对象(已将Json字符串转换成对象)
        UserInfo user = userInfoRedisService.getUserByToken(token);
        return user;
    }
}
